<template>
  <div class="container">
    <el-form :model="dataForm" @submit.native.prevent>
      <el-form-item>
        <el-input
            ref="search-ref"
            v-model="dataForm.param"
            clearable
            placeholder="[F1]:条码/自编码/名称"
            prefix-icon="el-icon-s-shop"
            suffix-icon="el-icon-search"
            @change="handleSearch">
        </el-input>
      </el-form-item>
    </el-form>
    <!-- 商品搜索弹窗 -->
    <el-dialog
        :title="'请选择商品，' + dataListToChoose.length + ' 个匹配项'"
        :visible.sync="chooseDialogVisible"
        append-to-body
        width="40%">
      <commodity-list :data-list="dataListToChoose" class="choose-list"></commodity-list>
      <span slot="footer" class="dialog-footer">
      <el-button @click="chooseDialogVisible = false">取 消</el-button>
    </span>
    </el-dialog>
  </div>
</template>

<script>
import {mapGetters} from 'vuex'
import CommodityList from '@/views/store/components/CommodityList.vue'
import {getStorePromotionDiscount} from '@/api/settle'

var Mousetrap = require('mousetrap')
export default {
  name: 'CartSearchBar',
  components: {
    CommodityList
  },
  data () {
    return {
      dataForm: {
        param: ''
      },
      chooseDialogVisible: false,
      dataListToChoose: []
    }
  },
  computed: {
    ...mapGetters([
      'stationId',
      'operator',
      'stockList',
      'cartList',
      'cartVisible',
      'cartGoodsList'
    ])
  },
  mounted () {
  },
  methods: {
    handleSearch (value) {
      console.log('handleSearch')
      console.log(value)
      if (!value) {
        return false
      }
      var tmpList = this.stockList.filter(item => item.barcode.indexOf(value) > -1 || item.commodityName.indexOf(value) > -1)
      if (tmpList.length === 1) {
        // 判断该商品是否已下架，已下架则提示不允许售卖
        if (tmpList[0].stockStatus === 0) {
          this.$message.warning('该商品已下架，不允许销售！')
          return false
        }
        console.log('addToCartList')
        this.$store.dispatch('addToCartList', tmpList[0])
        this.$store.dispatch('updateCouponSelect', {})
        this.dataForm.param = ''
      } else if (tmpList.length > 1) {
        // 打开选择弹窗
        console.log('打开选择弹窗')
        this.dataListToChoose = tmpList
        this.chooseDialogVisible = true
      } else {
        this.$message.warning('找不到对应的商品')
      }
    },
    // 获取商品优惠金额
    getGoodsDiscount () {
      console.log(this.cartGoodsList)
      var params = {
        stationId: this.stationId,
        commodityIds: this.cartGoodsList.map(item => item.id).join(','),
        commodityNums: this.cartGoodsList.map(item => item.nums).join(',')
      }
      // 清空优惠
      this.$store.dispatch('setGoodsDiscountAmount', {})
      if (this.cartGoodsList.length < 1) {
        return false
      }
      getStorePromotionDiscount(params).then(res => {
        console.log('getStorePromotionDiscount')
        console.log(res)
        // 更新优惠
        if (!isNaN(res.data.goodsDiscountAmount)) {
          this.$store.dispatch('setGoodsDiscountAmount', res.data)
        }
      }).catch(err => {
        console.log(err)
      })
    },
    bindKeyboard () {
      Mousetrap.bind('f1', () => {
        if (this.cartVisible) {
          // 焦点聚焦在油枪输入框内
          this.$nextTick(() => {
            this.$refs['search-ref'].focus()
          })
        }
      })
    }
  },
  watch: {
    // 深度监听，并自动关闭选品弹窗
    cartList: {
      handler (newName, oldName) {
        console.log('cartList change')
        this.chooseDialogVisible = false
        this.dataForm.param = ''
        this.$refs['search-ref'].focus()
        this.getGoodsDiscount()
      },
      deep: true
    },
    cartVisible: function (newVal, oldVal) {
      if (newVal) {
        setTimeout(() => {
          this.bindKeyboard()
        }, 500)
      }
    }
  }
}
</script>

<style scoped>
.choose-list {
  height: 500px;
  overflow-y: auto;
}
</style>